<?php

/*
 * 通用函数
 * @since 1.0 2014-12-29 by sutroon
 */

/**
 * 检测用户登录
 * @param array $data 登录数据
 * @return boolean
 * @since 1.0 <2015-10-19> SoChishun Added.
 */
function user_check_login(&$data = '', $refresh = true) {
    $data = session('login');
    if (!$data) {
        return false;
    }
    // 页面刷新的时候刷新用户登录信息,以同步个人资料编辑 2016-2-15 SoChishun Added.
    if ($refresh) {
        $m_login = new \XWAM\Model\LoginModel();
        $status = $m_login->refresh_login_info($data);
        if (true === $status) {
            session('login', $data);
        } else if ('E_ACCOUNT_DISABLED' == $status) {
            E('帐户已禁用!');
        }
    }
    return true;
}

/**
 * 检查权限名称
 * @param string $value 权限值
 * @param string $field 字段
 * @return boolean
 * @since 1.0 <2015-8-4> SoChishun Added.
 * @since 1.1 <2015-8-6> SoChishun 新增$role_id参数
 * @since 1.2 <2016-4-8> SoChishun 重构.
 * @since 2.0 2016-6-2 SoChishun equal_permission 重构为 sofn_auth,新增$field字段
 */
function sofn_auth($value, $field = 'code') {
    if (!$value) {
        return false; // 参数无效
    }
    if (!user_check_login($login_data)) {
        return false; // 未登录
    }
    if (empty($login_data['role_ids'])) {
        return false; // 角色未分配
    }
    $role_id = $login_data['role_ids']; // 角色编号
    // get rule
    $cache_name = 'think_auth_rule_' . $field;
    $rules = S($cache_name);
    if (!$rules) {
        $m_rule = new XWAM\Model\RuleModel();
        $rules = $m_rule->getField($field . ', id');
        S($cache_name, $rules, 15);
    }
    if (!isset($rules[$value])) {
        return false; // 权限记录不存在
    }
    $rule_id = $rules[$value]; // 节点编号
    // groups
    $cache_name = 'think_auth_group';
    $groups = S($cache_name);
    if (!$groups) {
        $m_group = new \XWAM\Model\RoleModel();
        $groups = $m_group->getField('id, rules');
        S($cache_name, $groups, 15);
    }
    if (!isset($groups[$role_id])) {
        return false; // 角色(组)不存在
    }
    $srules = $groups[$role_id];
    if ('*' == $srules) {
        return true;
    }
    $arules = explode(',', $srules);
    if (!in_array($rule_id, $arules)) {
        return false; // 角色未包含该权限规则
    }
    return true;
}

/**
 * 检测系统环境
 * @since 1.0 <2015-9-28> SoChishun Added.
 */
function sofn_check_env() {
    version_compare(PHP_VERSION, '5.3.0', '<') and exit('系统需要PHP版本5.3.0以上环境(当前版本:' . PHP_VERSION . ').');
    function_exists('mysql_close') or exit('系统需要MySQL环境支持.');
    $ver = '';
    if (function_exists("mysql_get_server_info")) {
        $ver = mysql_get_server_info();
    }
    if (!$ver) {
        $result = $this->query('select VERSION()');
        $ver = current($result[0]);
    }
    version_compare($ver, '5.1.38', '<') and exit('系统需要MySQL版本5.1.0以上环境(当前版本:' . $ver . ').');
}

/**
 * 通用获取状态名称方法
 * @param string $v 值
 * @param string $type 类型
 *      yesno=否|是,activate=未激活|已激活,approval=未审核|已审核,startstop=已停止|已启动|已暂停,enable=已禁用|已启用,login:登出|登入,user=正常|待审核|禁用,sex=女士|先生|保密,marital=未婚|已婚|保密
 * @return string
 * @since 1.0 2014-7-7 by sutroon, 2014-12-3 新增$undefined
 * @example {$vo.state|sofn_get_state_text=user,###}
 */
function sofn_get_state_text($type, $v, $undefined = null) {
    $set = false;
    switch (strtolower($type)) {
        case 'user-state':
            $set = array('0' => '待审核', '1' => '正常', '3' => '冻结', '4' => '禁用', '7' => '注销', '14' => '回收站');
            break;
        case 'online-state':
            $set = array('0' => '离线', '1' => '在线', '2' => '隐身', '3' => '离开', '5' => '忙碌');
            break;
        case 'start-stop':
            $set = array('0' => '已停止', '1' => '已启动', '2' => '已暂停');
            break;
        case 'activate-state':
            $set = array('0' => '未激活', '1' => '已激活');
            break;
        case 'yes-no':
            $set = array('0' => '否', '1' => '是', 'N' => '否', 'Y' => '是', 'F' => '否', 'T' => '是');
            break;
        case 'success-fail':
            $set = array('0' => '失败', '1' => '成功', 'N' => '失败', 'Y' => '成功');
            break;
        case 'display-hide':
            $set = array('0' => '隐藏', '1' => '显示', 'N' => '隐藏', 'Y' => '显示');
            break;
        case 'approval-state':
            $set = array('0' => '未审核', '1' => '已审核', '4' => '已关闭');
            break;
        case 'enable':
            $set = array('0' => '已禁用', '1' => '已启用');
            break;
        case 'login':
            $set = array('0' => '已登出', '1' => '已登入');
            break;
        case 'sex':
            $set = array('0' => '女士', '1' => '先生', '2' => '保密');
            break;
        case 'marital':
            $set = array('0' => '未婚', '1' => '已婚', '2' => '保密');
            break;
        case 'cti-call-result':
            $set = array('ANSWERED' => '应答', 'NO ANSWER' => '无应答', 'CONGESTION' => '堵塞', 'BUSY' => '忙音', 'FAILED' => '失败');
            break;
        case 'cti-channel-state':
            $set = array('0' => '空闲', '1' => '正在呼叫', '2' => '通话中', '3' => '呼叫成功', '4' => '呼叫失败');
            break;
        case 'cti-call-forwarding-type':
            $set = array('0' => '', '1' => '无条件转接', '2' => '忙时转移', '3' => '无应答或不可用时转移');
            break;
        case 'message-send-state':
            $set = array('0' => '未发送', '1' => '发送成功', '2' => '发送失败');
            break;
        case 'record-source':
            $set = array('import' => '导入', 'add' => '添加', 'generate' => '生成');
            break;
        case 'pay-type':
            $set = array('0' => '后付费', '1' => '预付费');
            break;
        case 'settlement-status':
            $set = array('0' => '未结算', '1' => '已结清', '2' => '部分结算');
            break;
        case 'confirm':
            $set = array('0' => '未审核', '1' => '审核通过', '4' => '审核拒绝');
            break;
        case 'input-type':
            $set = array('text' => '字符输入框', 'int' => '数字输入框', 'decimal' => '小数输入框', 'email' => '邮件输入框', 'mobile' => '手机号码输入框', 'telphone' => '电话号码输入框', 'date' => '日期选择框(xxxx-xx-xx)', 'datetime' => '日期和时间选择框(xxxx-xx-xx xx:xx:xx)', 'time' => '时间选择框(xx:xx)', 'select' => '下拉选择框', 'radio' => '单选框', 'checkbox' => '复选框', 'textarea' => '多行文本框', 'editor' => '可视化编辑器', 'file' => '文件上传框');
            break;
        case 'product-sale-state': // 商品销售状态
            $set = array('0' => '下架', '1' => '上架');
            break;
        case 'product-invoicing-operate-type': // 商品进销存操作类型 2014-12-23 by sutroon
            $set = array('SELL-RETURN' => '销售退货(入库)', 'SALE' => '销售出库', 'PURCHASE' => '采购入库', 'INTERNAL' => '内部出库', 'INVENTORY' => '盘点调仓');
            break;
        case 'customer-appointment-status': // 客户预约状态 2014-12-24 by sutroon
            $set = array('0' => '未回访', '1' => '回访成功', '2' => '回访失败', '4' => '放弃回访');
            break;
        case 'customer-appointment-type': // 客户预约来源 2014-12-24 by sutroon
            $set = array('USER' => '自定义', 'ORDER' => '订单回访');
            break;
        case 'customer-buy-interested': // 客户购买意向 2014-12-25 by sutroon
            $set = array('0' => '普通', '1' => '意向购买', '2' => '非常兴趣');
            break;
        case 'is-search-condition':
            $set = array('N' => '不搜索', 'EQ' => '精确匹配', 'LIKE' => '模糊匹配', 'ELT' => '小于等于', 'EGT' => '大于等于');
            break;
        case 'settlement-state':
            $set = array('0' => '未结算', '1' => '已结算');
            break;
        case 'invoicing-direction':
            $set = array('I' => '入库', 'O' => '出库');
            break;
        case 'channel-type':
            $set = array('page' => '单独页面', 'document-list' => '文章栏目', 'file-list' => '下载栏目','node'=>'普通节点', 'ulink' => '分类链接', 'url' => '链接地址');
            break; 
    }
    $str = false;
    if ($set) {
        if (array_key_exists($v, $set)) {
            $str = $set[$v];
        } else if (array_key_exists('*', $set)) {
            $str = $set['*'];
        } else {
            $str = '';
        }
    }
    if (false === $str) {
        $str = is_null($undefined) ? "[$type|$v]" : $undefined;
    }
    return $str;
}
function get_order_state_text($key='xcrm',$value=''){
    $data=array();
    $str = false;
    if ($set) {
        if (array_key_exists($v, $set)) {
            $str = $set[$v];
        } else if (array_key_exists('*', $set)) {
            $str = $set['*'];
        } else {
            $str = '';
        }
    }
    if (false === $str) {
        $str = is_null($undefined) ? "[$type|$v]" : $undefined;
    }
    return $str;    
}

/**
 * 获取存储过程标准返回值描述
 * @param int $code 返回代码
 * @param array $arr_msg 覆盖的描述
 * @return string 代码对应的描述
 * @since 1.0 2014-10-16 by sutroon
 * @example sofn_get_procedure_result_text($result['@oint_result'],array('1'=>'注册成功,请重新登录','4300'=>'手机号码已存在'));
 */
function sofn_get_procedure_result_text($code, $arr_msg = array()) {
    $arr_msg = $arr_msg + array(1 => '执行成功', 4000 => '系统错误', 4100 => '参数错误', 4200 => '状态有误', 4300 => '记录已存在', 4400 => '记录不存在', 4500 => '值不在范围内(小于下限或大于上限)');
    return array_key_exists($code, $arr_msg) ? $arr_msg[$code] : '未知错误' . $code;
}

/**
 * 生成序列号
 * <br />把12位时间数值压缩成7-8位字母+数字组合字符串,重点是加上用户编号后将永不重复哈
 * <br />用法：$serial_no = sofn_generate_serial('KH' . $this->user_login_data['id']);
 * <br />示例：160121054346(12位,date('ymdhis'))压缩后QBVF4346(8位,sofn_generate_serial())
 * @param string $serial_no 序号前缀，如:'KH' . $this->user_login_data['id']
 * @return string 如：QBVF295
 * @since VER:1.0; DATE:2016-1-21; AUTHOR:SoChishun; EMAIL:14507247@qq.com; DESC:Added.
 */
function sofn_generate_serial($serial_no = '') {
    $time = date('y-m-d-h-i-s'); // 16-01-22-05-26-31
    $atime = explode('-', $time);
    foreach ($atime as $stime) {
        $itime = $stime * 1;
        if ($itime < 26) {
            // 65(A)-90(Z)
            $serial_no.=chr(65 + $itime);
            continue;
        }
        // 48(0)-57(9)
        if ($itime >= 48 && $itime <= 57) {
            $serial_no.=chr($stime);
            continue;
        }
        $serial_no.=$stime;
    }
    return $serial_no;
}

/**
 * 解析htmlselect的选项单元
 * @param string $str 格式：value:text\n
 * @since 1.0 <2015-10-20> SoChishun Added.
 */
function parse_htmlselect_options($str, $value = '', $split1 = ':', $split2 = ';') {
    $out = '';
    if (!$split2) {
        $split2 = "\n";
    }
    $list = explode($split2, $str);
    foreach ($list as $row) {
        $arow = explode($split1, $row, 2);
        if (count($arow) > 1) {
            $out.='<option value="' . $arow[0] . '"' . ($value == $arow[0] ? 'selected="selected"' : '') . '>' . $arow[1] . '</option>';
        } else {
            $out.='<option value="' . $arow[0] . '"' . ($value == $arow[0] ? 'selected="selected"' : '') . '>' . $arow[0] . '</option>';
        }
    }
    return $out;
}

function afn_write_log($path, $flag) {
    if (!$path) {
        return;
    }
    if ('ALL' == $flag) {
        $flag = false;
    }
    $systypes = array('EMERG', 'ALERT', 'CRIT', 'ERR', 'WARN', 'NOTIC', 'INFO', 'DEBUG', 'SQL');
    $file = fopen(sofn_path_rtoa($path), 'r');
    $i = 1;
    $n = 0;
    echo '<div class="content">';
    echo '<div class="section">'; // section
    while (!feof($file)) {
        $sline = trim(fgetss($file, 2048));
        if (!$sline) {
            continue;
        }
        $n++;
        if ('[' == $sline[0]) {
            if ($n > 1) {
                echo '</div><div class="section">';
            }
            echo '<div class="title">', $sline, '</div>';
        } else {
            $type = substr($sline, 0, strpos($sline, ':'));
            if ($flag) {
                if ('OTHER' == $flag && in_array($type, $systypes)) {
                    continue;
                } else if ('OTHER' != $flag && $flag != $type) {
                    continue;
                }
            }
            echo '<div class="log">', $i, '. <a href="?module=', $module, '&logfile=', $logfile, '&flag=', $type, '">', $type, '</a>', substr($sline, strlen($type)), '</div>';
            $i++;
        }
    }
    fclose($file);
    echo '</div>'; // /section
    echo '</div>';
    echo '<div class="sum">共 ', $i, ' 条日志</div>';
}

/**
 * 翻译
 * @param type $val
 * @param type $type
 * @return string
 * @since 1.0 2016-2-1 SoChishun Added.
 */
function afn_get_text($val, $type = '') {
    if (!$type) {
        return '';
    }
    $data = array();
    switch ($type) {
        case 'VAR_TYPE':
            $data = array('C' => '字符', 'N' => '数字', 'T' => '文本', 'A' => '数组', 'E' => '枚举');
            break;
        case 'VAR_GROUP':
            $data = array('B' => '基本', 'C' => '内容', 'U' => '用户', 'S' => '系统');
            break;
    }
    return array_key_exists($val, $data) ? $data[$val] : '';
}

// 2016-4-15
function sofn_parse_customer_labels($labels, $url) {
    $alabels = explode(' ', $labels);
    $str = '';
    foreach ($alabels as $slabel) {
        $str.='<a href="' . str_replace('varlabel', $slabel, $url) . '">' . $slabel . '</a> ';
    }
    return $str;
}

/**
 * 语音管理-获取语音路径
 * @param string $tag
 * @return type
 */
function get_voc_url($tag) {
    switch ($tag) {
        case 'moh':
            return 'http://' . $_SERVER['SERVER_NAME'] . ':8897';
        case 'sounds':
            return 'http://' . $_SERVER['SERVER_NAME'] . ':8896';
        case 'rec':
            return 'http://' . $_SERVER['SERVER_NAME'] . ':8898/';
    }
    return '';
}

/**
 * 处理录音文件地址
 * @param string $file
 * @return string
 * @since 1.0 2014-7-24 by sutroon
 */
function parse_voc_path($file) {
    // q-2000-18679753678-20140814-223101-1408026661.3643.WAV
    // /monitor/2014/08/10/
    if (strpos($file, '-') === false) {
        return $file;
    }
    $arr = explode('-', $file);
    $path = $arr[3];
    return substr($path, 0, 4) . '/' . substr($path, 4, 2) . '/' . substr($path, 6) . '/' . $file;
}

/**
 * 获取通道状态名称
 * @param int $v
 * @return string
 * @since 1.0 2014-7-2 by sutroon
 * 1=接入(策略外呼后转分机)[呼入费率组],2=呼出(策略外呼)[呼出费率组],3=网内(分机互打),4=来话(系统被叫来话),5=外呼(分机直接呼出)[呼出费率组],6=签入(分机签入队列),7=签出(分机签出队列)
 */
function sofn_get_channel_direction_text($v) {
    switch ($v) {
        case '1':
            return '接入';
        case '2':
            return '呼出';
        case '3':
            return '网内';
        case '4':
            return '来话';
        case '5':
            return '外呼';
        case '6':
            return '签入';
        case '7':
            return '签出';
        case '8':
            return '未接';
    }
    return '未知' . $v;
}

// cdr 成功或失败字段 2016-3-19
function sofn_get_disposition_text($v) {
    if ('ANSWERED' == $v) {
        return '成功';
    }
    return '<span style="color:#F00">失败</span>';
}
